import {NavigationActions} from 'react-navigation';

let _navigator;
let navigationState = null;
function setTopLevelNavigator(navigatorRef) {
    _navigator = navigatorRef;
}

function navigate(routeName, params) {
    _navigator && _navigator.dispatch(
        NavigationActions.navigate({
            routeName,
            params,
        }),
    );
}

function pop() {
    _navigator && _navigator.dispatch(NavigationActions.back());
}


function isRootScreen() {

    if (_navigator) {
        if (_navigator.index == null) {
            return true;
        }

        if (_navigator.index > 0) {
            return false;
        }

        return (
            !_navigator.routes || !navigator.routes.find(route => !isRootScreen(route))
        );
    } else {
        return false;
    }
}

function onNavigationStateChange(pre, next) {
    navigationState = next;
}

function getCurrentScreenPageName() {
    if (navigationState) {
        return tranverseRoutes(navigationState);
    }
    return null;
}

function tranverseRoutes(state) {
    if (state.routes) {
        return tranverseRoutes(state.routes[state.index]);
    }
    else {
        return state.routeName;
    }
}

// add other navigation functions that you need and export them
const NavigationService = {
    navigate,
    setTopLevelNavigator,
    pop,
    isRootScreen,
    onNavigationStateChange,
    getCurrentScreenPageName
};
export default NavigationService;
